import datetime
import logging
import os
import time
import random
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import simplejson as json

import py.datamodel

class Importer(webapp.RequestHandler):
       
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'

        if self.request.get("viewer") == "null":
            visitCount = py.datamodel.UnknownVisit()
            visitCount.owner = self.request.get("owner")
            visitCount.ownerId = self.request.get("ownerId")
            visitCount.cookie = self.request.get("cookie")
            visitCount.param = self.request.get("param")
            visitCount.sessionId = self.request.get("sessionId")
            visitCount.ip = self.request.get("ip")
            visitCount.enterTime = datetime.datetime.fromtimestamp(float(self.request.get("enterTime")) / 1000)
            visitCount.exitTime = datetime.datetime.fromtimestamp(float(self.request.get("exitTime")) / 1000)
            visitCount.put()
            
        else:
            visitCount = py.datamodel.Visit()
            visitCount.owner = self.request.get("owner")
            visitCount.ownerId = self.request.get("ownerId")
            visitCount.viewer = self.request.get("viewer")
            visitCount.cookie = self.request.get("cookie")
            visitCount.param = self.request.get("param")
            visitCount.sessionId = self.request.get("sessionId")
            visitCount.ip = self.request.get("ip")
            visitCount.viewerId = self.request.get("viewerId")
            visitCount.enterTime = datetime.datetime.fromtimestamp(float(self.request.get("enterTime")) / 1000)
            visitCount.exitTime = datetime.datetime.fromtimestamp(float(self.request.get("exitTime")) / 1000)
            visitCount.put()
        
        # Updating counts
        owner = db.GqlQuery("SELECT * FROM Preferences WHERE owner = :1", self.request.get("ownerId"))
        if owner.count() == 0:
            # Create a new entity
            ownerRecord = py.datamodel.Preferences()
            ownerRecord.owner = self.request.get("ownerId")
            ownerRecord.counters = '{"knownVisitors":0}'
            ownerRecord.feedPrefs = ""
            ownerRecord.totalCount = 1
            ownerRecord.put()
        else:
            # Update the current entity
            record = owner.get()
            record.totalCount = record.totalCount + 1
            counters = json.loads(record.counters)
            if self.request.get("viewer") != "null" and self.request.get("viewer") != "" :
                if "knownVisitors" in counters:
                    counters["knownVisitors"] = counters["knownVisitors"] + 1 
                else:
                    counters["knownVisitors"] = 1
            record.counters = json.dumps(counters)
            record.put()
        
        sneakoscope = db.GqlQuery("SELECT * FROM Preferences WHERE owner = :1", "sneakoscope")
        record = sneakoscope.get()
        record.totalCount = record.totalCount + 1
        counters = json.loads(record.counters)
        if self.request.get("viewer") != "null" and self.request.get("viewer") != "" :
            if "knownVisitors" in counters:
            	counters["knownVisitors"] = counters["knownVisitors"] + 1 
            else:
            	counters["knownVisitors"] = 1
        record.counters = json.dumps(counters)
        record.put()
		
        self.response.out.write("Successfully inserted");


if __name__ == '__main__':
  application = webapp.WSGIApplication(
      [
        ('/.*', Importer),
      ],
      debug=True)

  wsgiref.handlers.CGIHandler().run(application)